<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
/*
* Notes:公共返回函数
* Create Date: 2018/10/28
* Create Time: 9:25
* Create by :张福来
* $code : 返回代码   200成功
* $message : 要返回的信息
* $data : 要返回的数据
*/
function apiResponse($code, $message, $data=[])
{
    $apireturn["code"] = $code;
    if (empty($message)) {
        $apireturn["message"] = "";
    } else {
        $apireturn["message"] = $message;
    }
    if (empty($data)) {
        $apireturn["data"] = "";
    } else {
        $apireturn["data"] = $data;
    }
    return $apireturn;
}

/*
* Notes: 发送短信方法封装
* Create Date: 2018/10/4
* Create Time: 上午9:33
* Create by :张福来
* $phonenum : 手机号码
* $modoules : 模版号
* $code : 模版中字段数组
*/
function sendSMS($phonenum, $modoules, $code = array())
{
    vendor('apiSms.SmsDemo');
    $sms = new SmsDemo();
    $response = $sms::sendSms($phonenum, $modoules, $code);
    return $response;
}

/**
 * @param array $arr 二维数组
 * @param $class        商品所属类型: 1 国际大厂配件 2 原厂配件
 * @param bool $type 是否是商品 true-商品 false-机油
 * @return array|mixed
 * @author zhenHong~
 */
function setGroupByArray(array $arr, $class, $type = false)
{
    $plist = [];
    if (array_key_exists($class, $arr)) {
        if ($type) {
            foreach ($arr[$class] as $key => $val) {
                $plist[$val['productName']]['goodsList'][] = $val;
            }
            $count = 0;
            foreach ($plist as $k => $v) {
                $plist[$k]['group_name'] = $k;
                $plist[$count] = $plist[$k];
                unset($plist[$k]);
                $count++;
            }
        } else {
            return $arr[$class];
        }
    }
    return $plist;
}

/**
 * @param $strName  订单前缀
 * @param $length   拼接长度
 * @return string
 * @author zhenHong~
 * 生成订单号
 * 方便后期拓展   将订单规则统一化
 */
function createOrderNumber($strName, $length)
{
    $numbers = range(1, 9);

    //shuffle 将数组顺序随机打乱
    shuffle($numbers);

    //取该数组中的某一段
    $number = array_slice($numbers, 0, $length);

    return $strName . time() . implode('', $number);
}

/**
 * @param $number
 * @return string
 * @author zhenhong
 * 获取订单状态
 */
function getOrderStatus($number)
{
    $word = '';
    switch ($number) {
        case '1':
            $word = '待付款';
            break;
        case '2':
            $word = '待服务';
            break;
        case '3':
            $word = '待评价';
            break;
        case '4':
            $word = '已完成';
            break;
        case '5':
            $word = '已取消';
            break;
        case '6':
            $word = '服务中';
            break;
    }
    return $word;
}

/**
 * @param $startTime
 * @param $endTime
 * @return array
 * @author zhenhong~
 * 后台时间段选择封装(通用)，前提你的数据库时间字段是int类型
 */
function getSelectTime($startTime, $endTime)
{
    $time = strtotime(date('Y-m-d'));

    $where = [];

    if ($startTime && !$endTime) {
        $start = strtotime($startTime);
        if ($start > $time) {
            $where = ['egt', $start];
        } else {
            $where = ['egt', $time];
        }
    }
    if ($endTime && !$startTime) {
        $end = strtotime($endTime);
        if ($end > $time) {
            $where = ['elt', $end];
        } else {
            $where = ['elt', $time];
        }
    }
    if ($startTime && $endTime) {
        $start = strtotime($startTime);
        $end = strtotime($endTime);
        if ($startTime >= $time && $end > $start) {
            $where = ['between', [$start, $end]];
        } else {
            $where = ['egt', $time];
        }
    }

    return $where;
}

/**
 * @param $lat1 纬度1
 * @param $lng1 经度1
 * @param $lat2 纬度2
 * @param $lng2 经度2
 * @return float
 * @desc 根据两点之间的经纬度算距离
 * @author zhenhong~
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000; //星球半径

    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;

    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;

    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;

    return round($calculatedDistance);
}

/**
 * @return mixed|string
 * @author zhenhong~
 * 获取接口调用凭证 access_token
 * access_token 微信默认缓存是2小时,如果出现过多的重复请求,微信会给你返回错误信息
 * 这里我将请求到的 access_token 缓存起来
 */
function getAccessToken()
{
    $accessToken = \think\Cache::get('accessToken');
    if ($accessToken) {
        return $accessToken;
    } else {
        $wx = \think\Config::get('wxConfig');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $wx['appId'] . "&secret=" . $wx['appKey'];
        $result = get_curl_request($url, 'GET');
        $resultArr = json_decode($result, true);
        \think\Cache::set('accessToken', $resultArr['access_token'], 7200);
        return $resultArr['access_token'];
    }
}


/**
 * @param $openId
 * @param $templateId
 * @param $data
 * @param $formId
 * @return mixed|string
 * @author zhenhong~
 * $openId - 当前用户openId
 * $templateId - 小程序模板ID
 * $data - 小程序模板规定的数据包
 * $formId - 下发条件(微信支付返回的prepay_id)
 */
function sendWxMessage($openId, $templateId, $data, $formId)
{
    $access_token = getAccessToken();
    $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token;
    $postData = [
        'touser' => $openId,
        'template_id' => $templateId,
        'data' => $data,
        'form_id' => $formId
    ];
    return get_curl_request($url, 'POST', json_encode($postData));
}


/**
 * @param $url
 * @param string $requestType
 * @param string $postData
 * @return mixed|string
 * @author zhenhong~
 * 发送 curl 的 post 和 get 请求
 * $url - 要请求的url地址
 * $requestType - 请求类型 get|post 默认get
 * $postData - post数据包 默认为空
 */

function get_curl_request($url, $requestType = 'GET', $postData = '')
{
    $curl = curl_init();
    //  抓取url
    curl_setopt($curl, CURLOPT_URL, $url);
    //  设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //  设置请求头数据格式
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type:application/json']);
    //  设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //  设置请求的最长时间
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    // 判断请求是否是post请求
    if ($requestType == 'POST') {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    }
    //  发送curl 请求
    $data = curl_exec($curl);
    //  返回最后一次的错误号
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    //  关闭url请求
    curl_close($curl);
    return $data;
}



function curl_request($url, $postData = '')
{
    $ch     = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        return false;
    }else{
        return $tmpInfo;
    }
}


function getTokenForYS(){
    $YSToken = \think\Cache::get('YSToken');
    if ($YSToken) {
        return $YSToken;
    } else {
        $url= "https://open.ys7.com/api/lapp/token/get";
        $data = [
            'appKey'=>'caf3065c691843c58f79a562e52ccf01',
            'appSecret'=>'32e79ee9472bea0db5e8214a46acaed9'
        ];
        $res = json_decode(curl_request($url,$data),true);
        $YSToken = $res['data']['accessToken'];
        \think\Cache::set('YSToken', $YSToken, 3600*24*5);
        return $YSToken;
    }

}    
